package com.ciwong.epaper.modules.pad.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.UserAccountInfo;
import com.ciwong.epaper.modules.login.LoginAccountAdapter;
import com.ciwong.epaper.modules.login.LoginContract;
import com.ciwong.epaper.modules.login.PopListItemListener;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.modules.pad.presenter.PadLoginPresenterImpl;
import com.ciwong.epaper.ui.NewLoginActivity;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.widget.CWProgressBar;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;


/**
 * 登录页面
 * Created by lqi on 2017/2/20.
 */
public class PadLoginDialogActivity extends Activity implements View.OnClickListener, LoginContract.LoginView {


    //    public  ViewGroup mContentView;
    private TextView mTvRriPwd;
    public TextView mTvErrPwd;
    private TextView mTvLogin;
    public EditText mEtNumber;
    public EditText mEtPwd;
    private ImageView mIvLoadMore;
    private RelativeLayout mRletLogain;


    private LoginAccountAdapter mAccountAdapter;
    private PopupWindow loginAccountPop;

    private UserInfoBase mUserInfoBase;

    private LoginContract.LoginPresenter mLoginPresenter;


    private int mSourceType;
    private boolean isLoginSuccess;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_pad_login_dialog);
        setFinishOnTouchOutside(false);

        Intent intent = getIntent();

        if (null != intent) {
            mSourceType = intent.getIntExtra("source_type", -1);
            Log.d(TAG, "#####mSourceType#########" + mSourceType);
            ComponentName component = intent.getComponent();
        }

        initView();
        initEvent();
        initData();

        mLoginPresenter = new PadLoginPresenterImpl(EApplication.getInstance(), this);

        final IntentFilter filter = new IntentFilter();
        filter.addAction(LoginToken.ACTION_LOGIN_SUCCESS);
        registerReceiver(mReceiver, filter);
    }


    private void initView() {
        mTvLogin = (TextView) findViewById(R.id.tv_login);
        mTvRriPwd = (TextView) findViewById(R.id.tv_retrieve_pwd);
        mTvErrPwd = (TextView) findViewById(R.id.tv_error_username_pwd);
        mEtNumber = (EditText) findViewById(R.id.et_login_number);
        mEtPwd = (EditText) findViewById(R.id.et_login_password);
        mIvLoadMore = (ImageView) findViewById(R.id.login_more);
        mRletLogain = (RelativeLayout) findViewById(R.id.rl_et_login_number);


    }

    private void initData() {
        loadData();

    }

    private void initEvent() {
        mTvLogin.setOnClickListener(this);
        mTvRriPwd.setOnClickListener(this);
        mIvLoadMore.setOnClickListener(this);

        mEtNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count == 0) {
                    mTvErrPwd.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0 && mEtNumber.hasFocus()) {
                    mEtPwd.setText("");
                }
            }
        });

        mEtPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count == 0) {
                    mTvErrPwd.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public OnLoginClickListener mOnLoginClickListener;


    public interface OnLoginClickListener {
        void getUserToken(String userName, String passWord);
    }

    public void setOnLoginClickListener(OnLoginClickListener onLoginClickListener) {
        mOnLoginClickListener = onLoginClickListener;
    }

    private static final String TAG = "PadLoginDialogActivity";

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_login) {
            String userName = mEtNumber.getText().toString().trim();
            String passWord = mEtPwd.getText().toString().trim();
            CWLog.e(TAG, "onClick: ");
            mLoginPresenter.validateCredentials(userName, passWord, "", "");
        } else if (id == R.id.tv_retrieve_pwd) {
            Intent intentLogin = new Intent(this, PadRetrievePwdActivity.class);

            startActivityForResult(intentLogin, RequestCode.PadResquestCode.REQ_CODE_TO_LOGIN);
        } else if (id == R.id.login_more) {
            showAccountPop();
        }
    }


    protected void loadData() {

        SerializableManager.getInstance().deSerialize(
                SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST, new BaseCallBack() {
                    @Override
                    public void success(Object data) {
                        try {
                            //防止遗漏缓存导致类型转换错误
                            List<UserAccountInfo> userAccountInfoList;
                            userAccountInfoList = (ArrayList<UserAccountInfo>) data;
                            if (null != userAccountInfoList && userAccountInfoList.size() > 0) {
                                initMorePop(userAccountInfoList);
                                initAccount(userAccountInfoList.get(0));
                            } else {
                                loginAccountPop = null;
                                initAccount(null);
                            }


                        } catch (ClassCastException e) {

                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                    }

                    @Override
                    public void failed(Object data) {
                    }
                }, false);
    }

    /**
     * 显示账号Pop
     */
    private void showAccountPop() {
        if (loginAccountPop == null) {
            return;
        }
        int paddingLeft = (int) getResources().getDimension(R.dimen.pop_padding_left);
        int paddingTop = (int) getResources().getDimension(R.dimen.pop_padding_top);
        loginAccountPop.showAsDropDown(mRletLogain, paddingLeft, paddingTop);

        int count = mAccountAdapter.getCount();
        if (count > 4) {
            count = 4;
        }
        loginAccountPop.update((int) (mEtNumber.getWidth() * 0.92),
                mEtNumber.getHeight() * count - 12);

        mIvLoadMore.setImageResource(R.drawable.pad_login_more_up);
    }


    private void initAccount(UserAccountInfo userAccountInfo) {
        if (null != userAccountInfo) {
            if (userAccountInfo.getPhonelogin()) {
                mEtNumber.setText(userAccountInfo.getPhoneNumber());
                mEtPwd.setText(userAccountInfo.getUserPwd());
            } else {
                mEtNumber.setText(String.valueOf(userAccountInfo.getUserId()));
                mEtPwd.setText(userAccountInfo.getUserPwd());
            }
        }
    }

    /**
     * 初始化账号登录Pop
     *
     * @param loginAccountInfos 已登录过用户集合
     */
    private void initMorePop(List<UserAccountInfo> loginAccountInfos) {
        if (loginAccountPop == null) {
            ListView listView = (ListView) View.inflate(this,
                    R.layout.login_account_pop, null);
            mAccountAdapter = new LoginAccountAdapter(this, loginAccountInfos);
            mAccountAdapter.setPopListItemListener(new PopListItemListener() {
                @Override
                public void deleteAccount(List<UserAccountInfo> userAccountInfoList, int position) {
                    loginAccountPop.dismiss();
                    if (userAccountInfoList == null) {
                        return;
                    }
                    userAccountInfoList.remove(position);
                    SerializableManager.getInstance().serialize(
                            SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST, (Serializable) userAccountInfoList, false);

                }
            });
            listView.setAdapter(mAccountAdapter);
            listView.setOnItemClickListener(
                    new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent,
                                                View view, int position, long id) {
                            UserAccountInfo userAccountInfo = (UserAccountInfo) parent.getItemAtPosition(position);

                            if (null != userAccountInfo) {
                                if (userAccountInfo.getPhonelogin()) {
                                    mEtNumber.setText(userAccountInfo.getPhoneNumber());
                                    mEtPwd.setText(userAccountInfo.getUserPwd());
                                } else {
                                    mEtNumber.setText(String.valueOf(userAccountInfo.getUserId()));
                                    mEtPwd.setText(userAccountInfo.getUserPwd());
                                }
                            }
                            loginAccountPop.dismiss();
                            mEtPwd.requestFocus();
                        }
                    });
            loginAccountPop = new PopupWindow(listView);
            loginAccountPop.setBackgroundDrawable(new BitmapDrawable());
            loginAccountPop.setOutsideTouchable(true);
            loginAccountPop.setFocusable(true);
            loginAccountPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mIvLoadMore.setImageResource(R.drawable.pad_login_more);
                }
            });
        } else {
            mAccountAdapter.clear();
            mAccountAdapter.addAll(loginAccountInfos);
        }
    }


    @Override
    public boolean isValidUserName(String userName) {
        Pattern pattern = Pattern.compile(
                "^[A-Za-z]{3,20}$|^[\u4e00-\u9fa5]{2,5}$|^[1-9][0-9]{4,15}$");
        boolean rs = pattern.matcher(userName.trim()).find();
        return rs;
    }

    @Override
    public boolean setUerNameError(String error) {
        if (!TextUtils.isEmpty(error)) {
            showToastError(error);
        }
        return true;
    }

    @Override
    public boolean setPasswordError(String error) {
        if (!TextUtils.isEmpty(error)) {
            showToastError(error);
        }
        return true;
    }

    @Override
    public boolean setSchoolNameError(String error) {
        if (!TextUtils.isEmpty(error)) {
            showToastError(error);
        }
        return true;
    }

    @Override
    public void showLoginProgress(boolean show) {
        if (show) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(PadLoginDialogActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            showCricleProgress(null);
        } else {
            hideCricleProgress();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.0f;
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onResume() {
        super.onResume();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1.0f;
        getWindow().setAttributes(lp);

    }

    @Override
    public void showLoginErrorMsg(String msg) {
        showToastError(msg);
    }

    @Override
    public void navigateToHome(boolean isBindPhone, String passWord) {
        isLoginSuccess = true;
        Intent inTeIntent = new Intent(LoginToken.ACTION_LOGIN_SUCCESS);
        inTeIntent.putExtra(LoginToken.IS_BIND_PHONE, isBindPhone);
        sendBroadcast(inTeIntent);
        if (!MeUtil.validatePassword(passWord)) {
            showPasswordDialog();
        } else {
            setResult(RESULT_OK, getIntent());
            finish();
        }
    }


    @Override
    public void onBackPressed() {

        setResult(RESULT_CANCELED);
        finish();
    }

    /**
     * 吐丝显示错误信息(方块)
     *
     * @param msg 字符串
     */
    public void showToastError(String msg) {
        ToastUtil.INSTANCE.toastInCenter(PadLoginDialogActivity.this, msg);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (LoginToken.ACTION_LOGIN_SUCCESS.equals(action)) {
                if (!isFinishing() && !isLoginSuccess) {
                    PadLoginDialogActivity.this.setResult(RESULT_OK);
                    finish();
                }
            }
        }
    };
    private CWProgressBar progressBar;

    /**
     * 显示全屏进度条
     *
     * @param msg
     */
    public void showCricleProgress(String msg) {

        if (progressBar == null) {
            progressBar = new CWProgressBar(this);
            progressBar.setCanceledOnTouchOutside(false);
            progressBar.setCancelable(true);


        }
        if (!isFinishing()) {
            if (!TextUtils.isEmpty(msg)) {
                progressBar.setMessage(msg);
            }
            if (!progressBar.isShowing()) {
                progressBar.show();
            }
        }

        if (null != mOnDismissListener) {
            progressBar.setOnDismissListener(mOnDismissListener);
        }

    }

    DialogInterface.OnDismissListener mOnDismissListener;

    public void setCricleProgressOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
        mOnDismissListener = onDismissListener;
    }

    /**
     * 关闭全屏进度条
     */
    public void hideCricleProgress() {
        if (progressBar != null && !isFinishing() && progressBar.isShowing()) {
            progressBar.dismiss();
        }
    }

/*
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			View v = getCurrentFocus();
			if (isShouldHideInput(v, ev)) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm != null) {
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
				}
			}

		}
		*/
/*if (getWindow().superDispatchTouchEvent(ev)) {
			return true;
		}*//*

		return super.dispatchTouchEvent(ev);
		// 必不可少，否则所有的组件都不会有TouchEvent了
		*/
/*if (getWindow().superDispatchTouchEvent(ev)) {
			return true;
		}
		return onTouchEvent(ev);*//*

	}
*/

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getRawX() > left && event.getRawX() < right
                    && event.getRawY() > top && event.getRawY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    InputMethodManager manager = null;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (manager == null) {
            manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        }
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }


    private CWDialog cWPwdDialog;

    /**
     * 密码简单提示
     */
    private void showPasswordDialog() {
        String msgTips = getString(R.string.dialog_pass_tips);
        if (cWPwdDialog != null && cWPwdDialog.isShowing()) {
            cWPwdDialog.dismiss();
        }
        cWPwdDialog = new CWDialog(this);
        cWPwdDialog.setMessagWidePadding(msgTips).setPositiveButton("修改密码", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                MeJumpManager.jumpToModifyPassword(R.string.go_back,
                        PadLoginDialogActivity.this);
                cWPwdDialog.dismiss();
            }
        }).setNegativeButtonTextColor(com.ciwong.mobilelib.R.color.color_light_green).show();

        cWPwdDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                cWPwdDialog.dismiss();
            }
        });
    }
}
